﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using DunSilverlight.Comm;
using System.Text;
using Telerik.Windows.Controls;

namespace DunSilverlight.Views
{
    public partial class ChangePasswordForm : UserControl
    {
        UserService.UserServiceClient ser = new UserService.UserServiceClient();
        public ChangePasswordForm()
        {
            InitializeComponent();
            ser.SaveOrUpdateCompleted += new EventHandler<UserService.SaveOrUpdateCompletedEventArgs>(ser_SaveOrUpdateCompleted);
        }

        //是否更改密码成功，如果关闭该窗口返回false
        private bool isSaveSuccess = false;
        public bool IsSaveSuccess
        {
            get
            {
                return this.isSaveSuccess;
            }
        }
       

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            string origin = tbOrigin.Password;
            string newPwd = tbNew.Password;
            string confirmPwd = tbConfirm.Password;

            if (string.IsNullOrEmpty(newPwd))
            {
                Tools.ShowMessage("密码不能为空，请重新输入", "", false);
                return;
            }

            if (newPwd != confirmPwd)
            {
                Tools.ShowMessage("输入的密码不一致，请重新输入", "", false);
                tbNew.Password = ""; ;
                tbConfirm.Password = "";
                tbOrigin.Password = "";
                return;
            }

            if (Convert.ToBase64String(Encoding.UTF8.GetBytes(origin)) != AppGlobal.CurrentUser.Password)
            {
                Tools.ShowMessage("原始密码错误，请重新输入", "", false);
                tbNew.Password = ""; ;
                tbConfirm.Password = "";
                tbOrigin.Password = "";
                return;
            }
            
            var user = AppGlobal.CurrentUser;
            string tmp = user.Password;
            user.Password = newPwd;
            ser.SaveOrUpdateAsync(JsonSerializerHelper.EntityToJson(user),tmp);

            Loger.WriteLog("修改密码", "");
        }

        void ser_SaveOrUpdateCompleted(object sender, UserService.SaveOrUpdateCompletedEventArgs e)
        {
            var user = JsonSerializerHelper.JsonToEntity<DunLibrary.User.User>(e.Result);
            if (user != null)
            {
                AppGlobal.CurrentUser = user;
                isSaveSuccess = true;
                (this.Parent as RadWindow).Close();


            }
            else
            {
                AppGlobal.CurrentUser.Password = e.UserState.ToString();
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}
